<template>
  <a-card :bordered="false" style="width: 100%">
    <search :config="searchConfig" @search="search" @getHeight="getHeight"/>
    <!-- table区域-begin -->
    <div>
      <vxe-grid
        ref="xGrid"
        :border="true"
        :resizable="true"
        :showOverflow="true"
        size="mini"
        :loading="loading"
        :height="pageHeight-seachHeight-94"
        :align="left"
        :columns="columns"
        :data="dataSource"
        :toolbar-config="tableToolbar"
        :checkbox-config="checkboxConfig"
        v-bind="vexConfig"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectChangeEvent"
      >
        <template #toolbar_buttons>
          <div class="table-operator">
            <a-button @click="handleAdd" type="primary" v-has="'internalUser:add'">新增</a-button>
            <a-button @click="batchDel" type="primary" v-has="'internalUser:delete'">删除</a-button>
            <a-button type="primary" @click="handleExportXls('企业用户导入模版')">模板下载</a-button>
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader1"
                      :action="importExcelUrl" @change="handleImportExcel">
              <a-button type="primary">导入</a-button>
            </a-upload>
            <a-button v-has="'internalUser:export'" @click="downExportXls('user_service')">导出</a-button>
            <a-button v-has="'internalUser:untie'" :disabled="selectedRowKeys.length<=0" @click="uboundOpenId">微信解绑
            </a-button>
            <a-button v-has="'internalUser:Initialize'" @click="initUserCache">
              初始化用户缓存
            </a-button>
          </div>
        </template>
        <template #detail="{ row,rowIndex }">
          <a @click="handleDetail(row)">{{ row.userName }}</a>
        </template>
        <template #avatarslot="{ row,rowIndex }">
          <a-avatar shape="square" :src="getAvatarView(row.avatar)" icon="user"/>
        </template>
        <template #status="{ row,rowIndex }">
          <a-switch :checked="row.status" size="small" @change="handleStatus(row,$event)"/>
        </template>
        <template #action="{ row,rowIndex }">
          <a v-has="'internalUser:update'" @click="handleEdit(row)">编辑</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多
              <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:" @click="handleChangePassword(row.userName)">修改密码</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:" @click="handleConfigView(row)">查看下属</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:" @click="handleConfig(row)">用户配置</a>
              </a-menu-item>
              <!--              <a-menu-item>-->
              <!--                <a href='javascript:' @click="handleConfigCust(row)">经销商配置</a>-->
              <!--              </a-menu-item>-->
              <!--              <a-menu-item>-->
              <!--                <a href='javascript:' @click="handleConfigTer(row)">门店配置</a>-->
              <!--              </a-menu-item>-->
              <a-menu-item v-has="'business:log'">
                <a href="javascript:" @click='handleBusiness("用户管理",row)'>日志</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync="ipagination.current"
            :page-size.sync="ipagination.pageSize"
            :total="ipagination.total"
            :pageSizes="ipagination.pageSizeOptions"
            @page-change="handlePageChange">
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->

    <user-modal ref="modalForm" @ok="modalFormOk"></user-modal>

    <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>

    <sys-user-agent-modal ref="sysUserAgentModal"></sys-user-agent-modal>

    <!-- 用户回收站 -->
    <user-recycle-bin-modal :visible.sync="recycleBinVisible" @ok="modalFormOk"/>

    <business-log ref="businessLog"></business-log>

    <config-role-pos ref="ConfigModal" @ok="saveUserRelation"></config-role-pos>

    <config-cust ref="ConfigCust" @ok="saveUserRelationCust"></config-cust>

    <config-ter ref="ConfigTer" @ok="saveUserRelationTer"></config-ter>
    <!--    查看下属-->
    <view-config-modal ref="ConfigView"></view-config-modal>
  </a-card>
</template>

<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import UserModal from '@page-modules/UserModal'
import PasswordModal from '@page-modules/PasswordModal'
import { getAction, postAction, putAction, getFileAccessHttpUrl } from '@/api/manage'
import { frozenBatch, queryDepartTreeList } from '@/api/api'
import SysUserAgentModal from '@page-modules/SysUserAgentModal'
import JInput from '@/components/cn-form/JInput'
import UserRecycleBinModal from '@page-modules/UserRecycleBinModal'
import CnDictSelectTag from '@/components/dict/CnDictSelectTag'
import ConfigCust from './modules/CustConfigModal'
import ConfigTer from './modules/TerConfigModal'
import ConfigRolePos from './modules/RolePosConfigModal'
import ViewConfigModal from './modules/ViewConfigModal'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'UserList',
  mixins: [PageListMixin],
  components: {
    SysUserAgentModal,
    UserModal,
    PasswordModal,
    JInput,
    UserRecycleBinModal,
    CnDictSelectTag,
    ConfigCust,
    ConfigTer,
    ConfigRolePos,
    ViewConfigModal
  },
  data() {
    return {
      userName: '', //查询下属的用户账号
      tokenHeader1: { 'Authorization': 'Bearer ' + Vue.ls.get(ACCESS_TOKEN).access_token },
      treeData: [],
      description: '这是用户管理页面',
      queryParam: {},
      recycleBinVisible: false,
      searchConfig: [
        {
          type: 'input',
          name: 'userName',
          placeholder: '用户账号'
        }, {
          type: 'input',
          name: 'realName',
          placeholder: '用户名称'
        },
        // {
        //   type: 'input',
        //   name: 'roleName',
        //   placeholder: '角色'
        // },
        {
          type: 'tree-select',
          dataType: 'org',
          name: 'departCode',
          placeholder: '所属组织'
        },
        {
          type: 'input',
          name: 'positionName',
          placeholder: '职位'
        },
      ],
      columns: [
        { type: 'checkbox', width: 60, fixed: 'left' },
        {
          fixed: 'left',
          title: '用户账号',
          field: 'userName',
          minWidth: 80,
          slots: { default: 'detail' }
        },
        {
          title: '用户名称',
          minWidth: 80,
          field: 'realName'
        },
        {
          title: '组织',
          minWidth: 80,
          field: 'departName'

        },
        {
          title: '用户类型',
          minWidth: 80,
          field: 'userType_dictText'
        },
        {
          title: '角色',
          field: 'roleNames',
          minWidth: 80
        },
        {
          title: '职位',
          field: 'positionNames',
          minWidth: 80
        },
        // {
        //   title: 'OA账号',
        //   minWidth: 80,
        //   field: 'jobNum'
        // },
        {
          title: '创建人',
          minWidth: 80,
          field: 'createName'
        },
        {
          title: '创建时间',
          minWidth: 80,
          field: 'createTime'
        },
        {
          title: '更新人',
          minWidth: 80,
          field: 'updateName'
        },
        {
          title: '更新时间',
          field: 'updateTime',
          minWidth: 80
        },
        {
          title: '用户状态',
          field: 'jobStatus',
          minWidth: 80
        },
        {
          title: '账号状态',
          minWidth: 80,
          fixed: 'right',
          field: 'status',
          slots: { default: 'status' }

        },
        {
          title: '操作',
          field: 'action',
          fixed: 'right',
          slots: { default: 'action' },
          minWidth: 120
        }

      ],
      isorter: {
        // userType: 1,
        permflag: 'user_page_impl'
      },
      url: {
        syncUser: '/process/extActProcess/doSyncUser',
        list: window._CONFIG['domianURL'] + '/cnUserController/getPageList',
        delete: window._CONFIG['domianURL'] + '/cnUserController/deleteByid',
        deleteBatch: window._CONFIG['domianURL'] + '/cnUserController/deleteBatch',
        detail: window._CONFIG['domianURL'] + '/cnUserController/getUserByIdOrCode',
        exportXlsUrl: window._CONFIG['domianURL'] + '/cnUserController/downloadTemplate',
        importExcelUrl: window._CONFIG['domianURL'] + '/cnUserController/importTemplate',
        saveUserRelation: window._CONFIG['domianURL'] + '/cnUserController/saveUserRelation',
        saveUserRelationCust: window._CONFIG['domianURL'] + '/cnUserController/saveUserPositionCust',
        saveUserRelationTer: window._CONFIG['domianURL'] + '/cnUserController/saveUserPositionTerm',
        openid: window._CONFIG['domianURL'] + '/cnUserController/uboundOpenIdByUser',
        initialize: window._CONFIG['domianURL'] + '/cnUserController/initUserCache',
      }
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${this.url.importExcelUrl}`
    }
  },

  created() {
    this.loadTree()
  },

  methods: {
    loadTree() {
      var that = this
      queryDepartTreeList({ permflag: 'user_page_impl_add_org' }).then((res) => {
        if (res.success) {
          that.treeData = []
          let treeList = res.result
          for (let a = 0; a < treeList.length; a++) {
            let temp = treeList[a]
            temp.isLeaf = temp.leaf
            that.treeData.push(temp)
          }
        }
      })
    },
    saveUserRelation(params) {
      postAction(this.url.saveUserRelation, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigModal.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigModal.confirmLoading = false
        //that.close();
      })
    },
    saveUserRelationCust(params) {
      postAction(this.url.saveUserRelationCust, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigCust.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigCust.confirmLoading = false
        //that.close();
      })
    },
    saveUserRelationTer(params) {
      postAction(this.url.saveUserRelationTer, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigTer.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigTer.confirmLoading = false
        //that.close();
      })
    },
    getAvatarView: function (avatar) {
      return getFileAccessHttpUrl(avatar)
    },
    handleView: async function (row) {
      this.$refs.modalForm.edit(row)
      this.$refs.modalForm.disableSubmit = true
    },
    // 行内切换状态
    async handleStatus(row, status) {
      let that = this
      this.loading = true
      await frozenBatch({ id: row.id, status: Number(status) }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.onClearSelected()
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.loadData()
      })
    },

    handleFrozen: function (id, status, userName) {
      let that = this
      //TODO 后台校验管理员角色
      if ('admin' == userName) {
        that.$message.warning('管理员账号不允许此操作！')
        return
      }
      frozenBatch({ ids: id, status: status }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleChangePassword(userName) {
      this.$refs.passwordmodal.show(userName)
    },
    //查看下属
    handleConfigView(userName) {
      this.$refs.ConfigView.showModal(userName)
      this.$refs.ConfigView.loadData(1)
    },

    handleConfigCust(userName) {
      this.$refs.ConfigCust.showModal(userName)
    },

    handleConfigTer(userName) {
      this.$refs.ConfigTer.showModal(userName)
    },

    handleAgentSettings(userName) {
      this.$refs.sysUserAgentModal.agentSettings(userName)
      this.$refs.sysUserAgentModal.title = '用户代理人设置'
    },
    passwordModalOk() {
      //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
    },
    uboundOpenId() {
      let ids = this.selectedRowKeys + ''
      getAction(this.url.openid, { ids }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    initUserCache() {
      this.loading = true
      getAction(this.url.initialize,).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },

    handleAdd: function () {
      this.$refs.modalForm.edit({ userType: 1 })
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>

